/*
 * PoissonGenerator.cpp
 *
 *  Created on: 2011-03-02
 *      Author: Jagger
 */

#include "PoissonGenerator.h"

#define __SJ__

Define_Module(PoissonGenerator)

void PoissonGenerator::initialize()
{
	lambda = par("lambda");

	#ifdef __SJ__
	// stala przyjeta - u mnie zczytywana z ini
	max_packets = 20;
	times = new simtime_t[max_packets];
	offset = 0;
	packets = 0;
	WATCH(packets);
	#endif
	AbstractGenerator::initialize();
}

simtime_t PoissonGenerator::getNextPacketArrivalTime(simtime_t lastPacketArrival)
{
	#ifdef __SJ__
	if(packets == 0){
		double sec = lastPacketArrival.dbl() + offset;
		while( (packets = poisson(lambda)) == 0 ) sec++;
		if(packets > max_packets) packets = max_packets;
		// losowanie czasow z przedzialu sekundy
		for(int i =0; i < packets; i++){
			double uni = uniform(0.0, 1.0);
			if(1.0 - uni < offset) offset = 1.0 - uni;
			times[i] = sec + uni;
		}
		// sortowanie
		for(int i = 0; i < packets - 1; i++)
			for(int j= 0; j < packets-1-i; j++)
				if(times[j] < times[j+1]){
					double mem = times[j].dbl();
					times[j] = times[j+1];
					times[j+1] = mem;
				}
	}
	return std::max(times[--packets], lastPacketArrival); // Szybki fix naprawiajacy blad z wysylaniem pakietow do przeszlosci

	#else
	return lastPacketArrival + poisson(lambda) * tick;
	#endif
}
